import React, { Component } from 'react';
import { Input } from 'antd';
import './index.less';
class InputText extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editable: false,
      error: false,
      value: '',
    };
  }
  componentDidMount() {
    this.input = React.createRef();
    if (this.props.value === '' || this.props.editable) {
      this.edit();
    }
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.value === '' || nextProps.editable) {
      this.edit();
    }
    if (nextProps.value !== this.props.value) {
      this.setState({
        value: nextProps.value,
      });
    }
  }
  edit = (e) => {
    this.setState(
      {
        editable: true,
        error: false,
      },
      () => {
        this.input.current.focus();
      }
    );
    if (e) {
      e.stopPropagation();
    }
  };
  onBlur = (e) => {
    const value = e.target.value;
    // 如果为空，则用之前的value
    if (!value && this.props.value) {
      this.setState({
        editable: false,
      });
      return;
    }
    this.setState(
      {
        value: value,
      },
      () => {
        this.setState({
          editable: false,
        });
      }
    );
    this.props.onChange && this.props.onChange(value);
  };
  handleChange = () => {};
  render() {
    const { value, color, width = 150 } = this.props;
    const { editable, error } = this.state;
    const style = error ? { borderColor: '#ff0000', width: width + 'px' } : { width: width + 'px' };
    const inputClassName = this.props.inputClassName !== undefined ? this.props.inputClassName : 'small';
    return (
      <span>
        {editable ? (
          <>
            <Input
              style={style}
              className={inputClassName}
              defaultValue={value}
              onBlur={this.onBlur}
              ref={this.input}
              onChange={this.handleChange}
              onClick={(e) => e.stopPropagation()}
            />
          </>
        ) : (
          <span onClick={this.edit} className='input-text-editor' style={{ color: color }}>
            {value}
          </span>
        )}
      </span>
    );
  }
}
export default InputText;
